#Copyright Ken Faulkner 2007.
from Common.logRoutine import *
import traceback
from Framework.Cache.Cache import Cache

class CacheManager( object ):
  """

  Takes a list of AudioDetails and figures out how to cache them.
  See, all tricky like dude....

  """
  def __init__(self, config ):
    self.config = config
    self.log = getLogger()
    
    self.cache = Cache( self.config )
    
  def saveAllAudio(self, audioDetailsList):
    """
    Save all the audio details entries.
    """

    self.log.info("CacheManager::saveAllAudio start")

    try:   

      dateDict = {}
      
      for day in audioDetailsList:
        date = day.date
        dayList = dateDict.setdefault( date, [])
        dayList.append( day )
        
      for date, dateList in dateDict.items():
        self.saveAudioForDate( date, dateList )
        
    except:
      self.log.error("CacheManager::saveAllAudio ex " + traceback.format_exc() )

  def saveAudioForDate(self, date, audioDetailsList):
    """
    Save all the audio details entries passed.
    All the audiodetails in the list should already be have the same
    date.
    """

    self.log.info("CacheManager::saveAudioForDate start")

    try:

      self.cache.set( date, audioDetailsList )
        
    except:
      self.log.error("CacheManager::saveAudioForDate ex " + traceback.format_exc() )


  def loadAllAudio(self, dateKeyList ):
    """
    Load all the audio details for a given date (which is generated into the key )
    """

    self.log.info("CacheManager::loadAllAudio start")

    audioList = []
    
    try:   
    
      l = []
      
      for key in dateKeyList:
        dayList = self.loadAudioForDate( key )
        
        l += dayList
        

      audioList = l
      
    except:
      self.log.error("CacheManager::loadAllAudio ex " + traceback.format_exc() )

    return audioList  
    

  def loadAudioForDate(self, dateKey ):
    """
    Load all the audio details for a given date (which is generated into the key )
    """

    self.log.info("CacheManager::loadAudioForDate start")

    dateSpecificAudioList = []
    
    try:   
    
      l = self.cache.get( dateKey )
      
      if l != None:
        dateSpecificAudioList = l
      
    except:
      self.log.error("CacheManager::loadAudioForDate ex " + traceback.format_exc() )

    return dateSpecificAudioList    
      

